package com.ag.webservice;

import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ag.admin.dao.AdminTbUserDAO;
import com.ag.bean.TbContact;
import com.ag.bean.TbDept;
import com.ag.bean.TbOaContact;
import com.ag.bean.TbUser;
import com.ag.bean.TbUserDept;
import com.ag.dao.TbContactDAO;
import com.ag.dao.TbDeptDAO;
import com.ag.dao.TbOaContactDAO;
import com.ag.dao.TbUserDeptDAO;
import com.ag.zhh.dao.DeptDAO;
import com.dcampus.user.webservice.I_Group;
import com.dcampus.user.webservice.I_ObjectService;
import com.dcampus.user.webservice.I_User;

/**
 * OA通讯录同步Service类
 * 
 * @author Administrator
 * 
 */
public class OAUserService extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(OAUserService.class);

	private static I_ObjectService service = null;
	static String ROLE_ID = "admin";
	static String SYSTEM_ID = "Student Management System";// ssm.getSubSystems()[0].getId();
	static String CATEGORY_ID = "user-manage";
	static String FUNCTION_ID = "view-user";

	static {
		Service serviceModel = new ObjectServiceFactory()
				.create(I_ObjectService.class);

		String serviceURL = "http://cas.gzfda.gov.cn/services/UserObjectService";
		// String serviceURL = "http://heaven.net/services/UserObjectService";

		try {
			service = (I_ObjectService) new XFireProxyFactory().create(
					serviceModel, serviceURL);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 主方法：保存所有OAuser（未完成）
	 * 用户部门表不存在的部门不能插
	 */
	public void saveAllOAUser() {
		//获取所有OAUSER
		I_User[] users = this.getAllOAUser();
		
		for (I_User user : users) {
			
			
			TbUserDept dept = null;//用户所属部门的引用
			
			String[] groups = user.getGroups();
			List<TbUserDept> userDepts = userDeptDAO.findByGId(groups[0]);
			if(userDepts != null && userDepts.size()>0) {
				//部门表中有此部门，查出此部门
				dept = userDepts.get(0);
			}else {
				//部门表中没有此部门,忽略此用户
				continue;
			}
			//用户所属部门获得
			
			//左外连接，找到现存的用户，如没有，则新建并设置ID
			TbUser contact = userDAO.findById(user.getId());
			if(contact == null) {
				contact = new TbUser();
				contact.setUId(user.getId());
			}
			//将OAUSER打包到用户bean中
			contact = packIUserIntoUser(user,contact,dept);
			//saveOrUpdate用户表
			userDAO.attachDirty(contact);
			userDeptDAO.attachDirty(dept);
			
			
		}
	}
	
	/**
	 * 将IUser打包返回一个新的OA通讯录对象（完成）
	 * 
	 * @param user
	 * @return
	 */
	private static TbUser packIUserIntoUser(I_User user,TbUser contact,TbUserDept dept) {
		
		//contact.setUId(user.getId());
		//contact.setCId(user.getId());
		contact.setUPhone(user.getMobilePhoneNumber());
		//contact.setCCellphone(user.getMobilePhoneNumber());
		//contact.setCTel(user.getPhoneNumber());
		contact.setUTel(user.getPhoneNumber());
		// contact.setCName(user.getName());
		contact.setUName(user.getName());
		contact.setOaAddress(user.getAddress());
		// contact.setOaCertificateId(user.getCertificateId());
		contact.setOaCode(user.getCode());
		contact.setOaDescri(user.getDescription());
		contact.setOaGender(user.getGender());
		contact.setOaHomeNumber(user.getHomeNumber());
		contact.setOaIdCard(user.getIdCard());
		contact.setUMail(user.getMail());
		contact.setOaMsn(user.getMsn());
		contact.setOaOfficeNumber(user.getOfficeNumber());
		contact.setOaQq(user.getQq());
		contact.setOaSex(user.getSex());
		contact.setOaZipCode(user.getZipCode());
		//contact.setTbU
		
		if(user.getGroups() != null && user.getGroups().length > 0){
			String[] groups = user.getGroups();
			
			contact.setOaGroups(groups[0]);
		}
		Set<TbUserDept> userDepts = contact.getTbUserDepts();
		if(userDepts == null) {
			userDepts = new HashSet<TbUserDept>();
		}
		userDepts.add(dept);
		contact.setTbUserDepts(userDepts);
		Set<TbUser> users = dept.getTbUsers();
		users.add(contact);
		dept.setTbUsers(users);
		
		// user.getRoles()
		
		// user.getPositions()
		// user.getGroups()
		return contact;
	}

	/**
	 * 访问OA系统，获取所有OA通讯录人
	 * 
	 * @return
	 */
	private I_User[] getAllOAUser() {
		I_User[] users = null;
		try {
			users = service.getAllUsers();
			if (users == null || users.length == 0) {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("OAUserService:getAllOAUser:异常");
			throw new RuntimeException("OAUserService:getAllOAUser:异常");
		}
		return users;
	}
	
	private I_Group getGroupByGId(String groupId) {
		I_Group group = null;
		try {
			group = service.getGroupOfId(groupId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return group;
	}
	
	/**
	 * 保存一个部门
	 * @param group
	 * @return
	 */
	public TbUserDept saveOneGroup(I_Group group) {
		TbUserDept dept = new TbUserDept();
		dept.setUdId(group.getId());
		dept.setGId(group.getId());
		//dept.setDName(group.getName());
		dept.setGCode(group.getCode());
		dept.setGDesc(group.getDescription());
		// StringBuilder admin = new StringBuilder();
		// for(String sadmin:group.getManagers()) {
		// admin.append(sadmin);
		// admin.append(",");
		// }
		// admin.substring(0, admin.length()-1);
		// dept.setGAdmin(admin.toString());
		//tbDeptDAO.attachDirty(dept);
		return dept;
	}
	
	

	/**
	 * 访问OA系统，获取所有OA部门
	 * 
	 * @return
	 */
	public I_Group[] getAllOAGroup() {
		I_Group[] groups = null;
		try {
			groups = service.getAllGroups();
			if (groups == null || groups.length == 0) {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("OAUserService:getAllOAGroup:异常");
			throw new RuntimeException("OAUserService:getAllOAGroup:异常");
		}
		return groups;
	}

	public boolean saveGroups() {
		boolean result = false;
		I_Group[] groups = getAllOAGroup();
		for (int i = 0; i < groups.length; i++) {
			// log.info("OAUserService:saveGroups----for循环GroupsID:"+groups[i].getId());
			// log.info("OAUserService:saveGroups----for循环GroupsName:"+groups[i].getName());
			// log.info("OAUserService:saveGroups----for循环GroupsCode:"+groups[i].getCode());
			// TbDept dept=GroupToDept(groups[i]);
			// log.info("OAUserService:saveGroups----for循环GroupsManager:"+dept.getGAdmin());
			// StringBuilder admin = new StringBuilder();
			// for(String sadmin:groups[i].getManagers()) {
			// admin.append(sadmin);
			// admin.append(",");
			// }
			// admin.substring(0, admin.length()-1);
			// String[] managers = groups[i].getManagers();
			// log.info("OAUserService:saveGroups----for循环GroupsManager前"+managers.length);
			// for(int j = 0;j<managers.length;j++) {
			// log.info("OAUserService:saveGroups----for循环GroupsManager:"+managers[j]);
			// }
			TbDept dept = GroupToDept(groups[i]);
			log.info("OAUserService:saveGroups----for循环GroupsID:"
					+ dept.getDId());
			log.info("OAUserService:saveGroups----for循环GroupsName:"
					+ dept.getDName());
			log.info("OAUserService:saveGroups----for循环GroupsCode:"
					+ dept.getGCode());
		}
		return result;
	}

	public TbDept GroupToDept(I_Group group) {
		TbDept dept = new TbDept();
		dept.setDId(group.getId());
		dept.setGId(group.getId());
		dept.setDName(group.getName());
		dept.setGCode(group.getCode());
		dept.setGDesc(group.getDescription());
		// StringBuilder admin = new StringBuilder();
		// for(String sadmin:group.getManagers()) {
		// admin.append(sadmin);
		// admin.append(",");
		// }
		// admin.substring(0, admin.length()-1);
		// dept.setGAdmin(admin.toString());
		tbDeptDAO.attachDirty(dept);
		return dept;
	}

	public void clearUpGroups() {
		Session session = null;
		Transaction tr = null;
		// String deleteMiddleTablesql = "delete from tb_dept_and_contact";
		// String deleteContactsql = "delete from tb_contact";
		// String sql = "delete from tb_oa_contact";
		String sql = "delete from tb_dept";
		log.info("cleanTableBySQL");
		try {
			DataSource ds = SessionFactoryUtils
					.getDataSource(getSessionFactory());
			Connection conn = ds.getConnection();

			session = getSession(true);

			tr = session.beginTransaction();
			Statement state = conn.createStatement();
			// 获取connection,执行静态SQL
			// Statement state = session.connection().createStatement();
			// state.executeQuery(deleteMiddleTablesql);
			// log.info("delete from tb_dept_and_contact");
			// state.executeQuery(deleteContactsql);
			// log.info("delete from tb_contact");

			state.executeQuery(sql);
			log.info("delete from tb_dept");

			tr.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (tr != null) {
				log.info("tr rollback");
				// tr.rollback();
			}
			if (session != null) {
				session.close();
			}

		}
	}

	/**
	 * 清除OA通讯录表
	 */
	public void clearUpDatabase() {
		log.info("clearUpDatabase");
		cleanTableBySQL();
	}

	private void cleanTableBySQL() {
		Session session = null;
		Transaction tr = null;
		// String deleteMiddleTablesql = "delete from tb_dept_and_contact";
		// String deleteContactsql = "delete from tb_contact";
		String sql = "delete from TB_CONTACT";
		log.info("cleanTableBySQL");
		try {
			DataSource ds = SessionFactoryUtils
					.getDataSource(getSessionFactory());
			Connection conn = ds.getConnection();

			session = getSession(true);

			tr = session.beginTransaction();
			Statement state = conn.createStatement();
			// 获取connection,执行静态SQL
			// Statement state = session.connection().createStatement();
			// state.executeQuery(deleteMiddleTablesql);
			// log.info("delete from tb_dept_and_contact");
			// state.executeQuery(deleteContactsql);
			// log.info("delete from tb_contact");

			state.executeUpdate(sql);
			log.info("delete from tb_oa_contact");

			tr.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (tr != null) {
				log.info("tr rollback");
				// tr.rollback();
			}
			if (session != null) {
				session.close();
			}

		}

	}

	/**
	 * 根据部门名查tbDept
	 * 
	 * @param deptName
	 * @return
	 */
	/*
	 * private Dept findDeptByDeptName(String deptName) { Dept dept = null;
	 * log.info("findDeptByDeptName——"+deptName); List<Dept> deptlist =
	 * deptDAO.findByProperty("DName", deptName); if (deptlist != null &&
	 * deptlist.size() > 0) { dept = deptlist.get(0); } return dept; }
	 */

	/**
	 * 保存单个的I_USER到OA通讯录中（未完成）
	 * 
	 * @param user
	 */
	public void saveSingleIUser(I_User user) {
		TbContact contact = this.packIUserIntoContact(user);
		Session session = null;
		log.info("saveSingleIUser");
		// String[] deptNames = user.getGroups();

		try {
			contactDAO.save(contact);
			/*
			 * session = getSession(true); session.save(contact); log.info("save
			 * contact"); session.flush(); session.clear();
			 * session.refresh(contact); log.info("refresh contact"); for
			 * (String deptName : deptNames) { log.info("添加部门——"+deptName); Dept
			 * dept = findDeptByDeptName(deptName);
			 * dept.getContacts().add(contact); session.update(dept);
			 * session.flush(); session.clear(); }
			 */
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (session != null) {
				session.close();
			}
		}

		// 保存到数据库中
	}

	/**
	 * 将IUser打包返回一个新的OA通讯录对象（完成）
	 * 
	 * @param user
	 * @return
	 */
	private static TbOaContact packIUserIntoOAContact(I_User user) {
		System.out.println("**************开始打包************************");
		TbOaContact oaContact = new TbOaContact();
		oaContact.setOaId(user.getId());
		oaContact.setOaMobilePhoneNumber(user.getMobilePhoneNumber());
		oaContact.setOaPhoneNumber(user.getPhoneNumber());
		oaContact.setOaName(user.getName());

		return oaContact;
	}

	

	/**
	 * 将IUser打包返回一个新的OA通讯录对象（完成）
	 * 
	 * @param user
	 * @return
	 */
	private static TbContact packIUserIntoContact(I_User user) {
		TbContact contact = new TbContact();
		contact.setCId(user.getId());
		contact.setCCellphone(user.getMobilePhoneNumber());
		contact.setCTel(user.getPhoneNumber());
		// contact.setCName(user.getName());
		contact.setCName(user.getName());
		contact.setOaAddress(user.getAddress());
		// contact.setOaCertificateId(user.getCertificateId());
		contact.setOaCode(user.getCode());
		contact.setOaDescri(user.getDescription());
		contact.setOaGender(user.getGender());
		contact.setOaHomeNumber(user.getHomeNumber());
		contact.setOaIdCard(user.getIdCard());
		contact.setOaEmail(user.getMail());
		contact.setOaMsn(user.getMsn());
		contact.setOaOfficeNumber(user.getOfficeNumber());
		contact.setOaQq(user.getQq());
		contact.setOaSex(user.getSex());
		contact.setOaZipCode(user.getZipCode());
		if(user.getRoles() != null && user.getRoles().length > 0){
			String[] roles = user.getRoles();
			StringBuilder role = new StringBuilder();
			for(int i = 0;i < roles.length;i++) {
				role.append(roles[i]);
				role.append(",");
			}
			role.substring(0, role.length() -1);
			contact.setOaRoles(role.toString());
		}
		
		if(user.getGroups() != null && user.getGroups().length > 0){
			String[] groups = user.getGroups();
			StringBuilder group = new StringBuilder();
			//log.info(arg0)
			for(int i = 0;i < groups.length;i++) {
				group.append(groups[i]);
				group.append(",");
			}
			group.substring(0, group.length() -1);
			contact.setOaGroups(group.toString());
		}
		
		if(user.getPositions() != null && user.getPositions().length > 0){
			String[] positions = user.getPositions();
			StringBuilder position = new StringBuilder();
			for(int i = 0;i < positions.length;i++) {
				position.append(positions[i]);
				position.append(",");
			}
			position.substring(0, position.length() -1);
			contact.setOaPositions(position.toString());
		}
		
		// user.getRoles()
		
		// user.getPositions()
		// user.getGroups()
		return contact;
	}

	@Resource(name = "DeptDAO")
	private DeptDAO deptDAO;
	@Resource(name = "TbContactDAO")
	private TbContactDAO contactDAO;
	@Resource(name = "TbOaContactDAO")
	private TbOaContactDAO oaContactDAO;
	@Resource(name = "TbDeptDAO")
	private TbDeptDAO tbDeptDAO;
	@Resource(name="adminTbUserDAO")
	private AdminTbUserDAO userDAO;
	@Resource(name="TbUserDeptDAO")
	private TbUserDeptDAO userDeptDAO;
}
